package com.lzs.bootsafety.common.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 获取spring管理的bean
 */
@Component
public class SpringContextAware implements ApplicationContextAware, BeanFactoryPostProcessor {

    private static ApplicationContext appContext=null;
    /**
     * 通过name获取bean
     * @param name
     * @return
     */
    public static Object getBean(String name){
        return appContext.getBean(name);
    }
    /**
     *通过class获取bean
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz){
        return appContext.getBean(clazz);
    }
    /**
     * 通过name和class获取bean
     * @param name
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBaen(String name,Class<T> clazz){
        return appContext.getBean(name,clazz);
    }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (appContext==null){
            appContext = applicationContext;
        }
    }
    /** Spring应用上下文环境 */
    private static ConfigurableListableBeanFactory beanFactory;
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        SpringContextAware.beanFactory=beanFactory;
    }
    /**
     *通过class获取bean
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBeans(Class<T> clazz){
        return beanFactory.getBean(clazz);
    }
}
